package com.meiyu.live;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.chatroom.ChatRoomService;
import com.netease.nimlib.sdk.chatroom.model.EnterChatRoomData;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.uinfo.UserInfoProvider;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.L;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.comm.UserConfig;
import com.meiyu.live.eventbus.LoginEvent;
import com.meiyu.live.ui.login.LoginActivity;
import com.meiyu.live.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;

public class BaseApplication extends Application {

    private static BaseApplication app;

    public static RequestQueue mVolleyQueue;
    private UMShareAPI mShareAPI;

    public static final Gson mGson = new GsonBuilder().disableHtmlEscaping().create();

    public static List<BaseActivity> task = new ArrayList<BaseActivity>();

    private final DisplayMetrics display = new DisplayMetrics();

    private String deviceId;

    private LocationClient mLocClient;

    public BDLocation getMlocation() {
        return mlocation;
    }

    public BDLocation mlocation;
    private MyLocationListenner myListener = new MyLocationListenner();


    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        mVolleyQueue = Volley.newRequestQueue(this);

        //极光推送初始化
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);

        // SDK初始化（启动后台服务，若已经存在用户登录信息， SDK 将完成自动登录）
        NIMClient.init(this, loginInfo(), options());

        initUmeng();

//        MobclickAgent.setDebugMode(true);
        //初始化ImageLoader
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
//                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions 内存缓存文件的最大长宽
//                .diskCacheExtraOptions(480, 800, null)  // 本地缓存的详细信息(缓存的最大长宽)，最好不要设置这个
//                .taskExecutor(...)
//                .taskExecutorForCachedImages(...)
//                .threadPoolSize(3) // default  线程池内加载的数量
//                .threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
//                .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通过自己的内存缓存实现
//                .memoryCacheSize(2 * 1024 * 1024)  // 内存缓存的最大值
//                .memoryCacheSizePercentage(13) // default
//                .diskCache(new UnlimitedDiscCache(cacheDir)) // default 可以自定义缓存路径
//                .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值
//                .diskCacheFileCount(100)  // 可以缓存的文件数量
                // default为使用HASHCODE对UIL进行加密命名， 还可以用MD5(new Md5FileNameGenerator())加密
//                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
//                .imageDownloader(new BaseImageDownloader(context)) // default
//                .imageDecoder(new BaseImageDecoder()) // default
//                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
//                .writeDebugLogs() // 打印debug log
                .build(); //开始构建
        ImageLoader.getInstance().init(config);
        //关闭ImageLoader的log
        L.writeDebugLogs(false);
        L.writeLogs(false);
        mShareAPI = UMShareAPI.get(this);
    }

    private void initUmeng() {
        //微信 appid appsecret
        PlatformConfig.setWeixin("wx5ae0047849183cbc", "a585f0ae035adfc6ef923819f4dfa900");
        //新浪微博 appkey appsecret
        PlatformConfig.setSinaWeibo("3301713491", "931dddea823d9e4628aa2e91d0197c5c");
        // QQ和Qzone appid appkey
        PlatformConfig.setQQZone("1105840667", "wGsDmyZZPTvxVRwB");
//        PlatformConfig.setQQZone("1105562527", "YrXoh6I4kh2QWdsF");
        Config.REDIRECT_URL = "http://sns.whalecloud.com/sina2/callback";

    }

    public Activity getCurrentActivity() {
        return task.get(task.size() - 1);
    }

    public static BaseApplication getApp() {
        return app;
    }

    // 如果返回值为 null，则全部使用默认参数。
    private SDKOptions options() {
        SDKOptions options = new SDKOptions();

        // 如果将新消息通知提醒托管给 SDK 完成，需要添加以下配置。否则无需设置。
//        StatusBarNotificationConfig config = new StatusBarNotificationConfig();
//        config.notificationEntrance = WelcomeActivity.class; // 点击通知栏跳转到该Activity
//        config.notificationSmallIconId = R.drawable.ic_launcher;
        // 呼吸灯配置
//        config.ledARGB = Color.GREEN;
//        config.ledOnMs = 1000;
//        config.ledOffMs = 1500;
        // 通知铃声的uri字符串
//        config.notificationSound = "android.resource://com.netease.nim.demo/raw/msg";
//        options.statusBarNotificationConfig = config;

        // 配置保存图片，文件，log 等数据的目录
        // 如果 options 中没有设置这个值，SDK 会使用下面代码示例中的位置作为 SDK 的数据目录。
        // 该目录目前包含 log, file, image, audio, video, thumb 这6个目录。
        // 如果第三方 APP 需要缓存清理功能， 清理这个目录下面个子目录的内容即可。
        String sdkPath = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/nim";
        options.sdkStorageRootPath = sdkPath;

        // 配置是否需要预下载附件缩略图，默认为 true
        options.preloadAttach = true;

        // 配置附件缩略图的尺寸大小。表示向服务器请求缩略图文件的大小
        // 该值一般应根据屏幕尺寸来确定， 默认值为 Screen.width / 2
//        options.thumbnailSize = ${Screen.width}/2;

        // 用户资料提供者, 目前主要用于提供用户资料，用于新消息通知栏中显示消息来源的头像和昵称
        options.userInfoProvider = new UserInfoProvider() {
            @Override
            public UserInfo getUserInfo(String account) {
                return null;
            }

            @Override
            public int getDefaultIconResId() {
                return R.drawable.image_loading;
            }

            @Override
            public Bitmap getTeamIcon(String tid) {
                return null;
            }

            @Override
            public Bitmap getAvatarForMessageNotifier(String account) {
                return null;
            }

            @Override
            public String getDisplayNameForMessageNotifier(String account, String sessionId,
                                                           SessionTypeEnum sessionType) {
                return null;
            }
        };
        return options;
    }

    // 如果已经存在用户登录信息，返回LoginInfo，否则返回null即可
    private LoginInfo loginInfo() {
        return UserConfig.getInstance().getIMLoginInfo();
    }

    private void initLocation() {
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setLocationNotify(true);
        option.setIsNeedAddress(true);
        option.setIsNeedLocationPoiList(true);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            mlocation = location;
            Log.e("location", location.getCity());
        }

    }

    public <T> void addRequest(Request<T> request) {
        mVolleyQueue.add(request);
    }

    public void addTask(BaseActivity act) {
        task.add(act);
    }

    public void removeTask(BaseActivity act) {
        task.remove(act);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        exitApp();
    }

    public SharedPreferences getShared() {
        return getSharedPreferences(Constant.APP_SHARED, 0);
    }

    public void exitApp() {
        mVolleyQueue.cancelAll(this);
        mLocClient.stop();
        try {
            for (Activity activity : task) {
                activity.finish();
            }
        } catch (Exception e) {
            Log.e("", "finish activity exception:" + e.getMessage());
        } finally {
            System.exit(0);
        }
    }

    public void logout(final boolean isError) {
        if (!TextUtils.isEmpty(UserConfig.getInstance().getOpenId()) && !TextUtils.isEmpty(UserConfig.getInstance().getThirdPlatform())) {
            SHARE_MEDIA platform = SHARE_MEDIA.QQ;
            switch (UserConfig.getInstance().getThirdPlatform()) {
                case "qq":
                    platform = SHARE_MEDIA.QQ;
                    break;
                case "wechat":
                    platform = SHARE_MEDIA.WEIXIN;
                    break;
                case "sina":
                    platform = SHARE_MEDIA.SINA;
                    break;
            }
            mShareAPI.deleteOauth(task.get(task.size() - 1), platform, new UMAuthListener() {
                @Override
                public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
//                    ToastUtil.show("退出第三方登录");
                }

                @Override
                public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

                }

                @Override
                public void onCancel(SHARE_MEDIA share_media, int i) {

                }
            });
        }
//        mVolleyQueue.cancelAll(getCurrentActivity());
        NIMClient.getService(AuthService.class).logout();
        UserConfig.getInstance().unlogin();

        getCurrentActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                EventBus.getDefault().post(new LoginEvent(false));
                if (isError) {
                    ToastUtil.show("帐号在其他设备登录");
                    Intent intent = new Intent(BaseApplication.getApp(), LoginActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    public void doIMLogin() {
        doIMLogin(null);
    }

    public void doIMLogin(RequestCallback callback) {
        String net_ease = UserConfig.getInstance().getNet_ease();
        String net_token = UserConfig.getInstance().getNet_token();
        if (TextUtils.isEmpty(net_ease) || TextUtils.isEmpty(net_token)) {
            BaseApplication.getApp().logout(true);
            return;
        }
        LoginInfo info = new LoginInfo(net_ease, net_token);
//        LoginInfo info = new LoginInfo("330149a5316ca7d8cefcab59f9eedac4", "1c0dd9f65f64cbce486de30b1bb2d6fe");
        if (callback == null) {
            NIMClient.getService(AuthService.class).login(info)
                    .setCallback(defaultCallback);
        } else {
            NIMClient.getService(AuthService.class).login(info)
                    .setCallback(callback);
        }

    }

    public void reEnterRoom(final RequestCallback callback, final EnterChatRoomData data) {
        BaseApplication.getApp().doIMLogin(new RequestCallback<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo param) {
                UserConfig.getInstance().setIMLoginInfo(param);
                NIMClient.getService(ChatRoomService.class).enterChatRoom(data)
                        .setCallback(callback);
                Log.w("", "IM登录成功");
            }

            @Override
            public void onFailed(int code) {
                Log.e("", "IM登录失败：" + code);
            }

            @Override
            public void onException(Throwable exception) {
                Log.e("", "IM登录错误：" + exception.getMessage());
            }
            // 可以在此保存LoginInfo到本地，下次启动APP做自动登录用
        });
    }

    RequestCallback<LoginInfo> defaultCallback =
            new RequestCallback<LoginInfo>() {
                @Override
                public void onSuccess(LoginInfo param) {
                    UserConfig.getInstance().setIMLoginInfo(param);
                    Log.w("", "IM登录成功");
                }

                @Override
                public void onFailed(int code) {
                    Log.e("", "IM登录失败：" + code);
                }

                @Override
                public void onException(Throwable exception) {
                    Log.e("", "IM登录错误：" + exception.getMessage());
                }
                // 可以在此保存LoginInfo到本地，下次启动APP做自动登录用
            };

    public int getWidth(float scale) {
        if (scale > 1) {
            return display.widthPixels;
        }
        return (int) (display.widthPixels * scale);
    }

    public int getHeight(float scale) {
        if (scale > 1) {
            return display.heightPixels;
        }
        return (int) (display.heightPixels * scale);
    }

}
